<template>
  <div>
    <div class="filter-items">
      <el-form ref="ruleForm" :model="filterForm">
        <el-row style="width:100%">
          <el-col :xl="6" :md="8" :sm="12" :xs="24" v-for="(f, index) in fields" :key="index">
            <el-form-item :label="f.label+' :'" :prop="f.field">
              <el-input
                v-if="!f.type || f.type === 'input'"
                :placeholder="f.placeholder || `请输入${f.label}`"
                class="filter-items_grain"
                :maxlength="f.maxlength"
                v-model="filterForm[f.field]"
                @input="filterForm[f.field] = $event"
                @change="(value: string) => { changeInput(value, f) }"></el-input>
              {{f.showSelect}}
              <el-select
                v-if="f.type === 'select' || f.type === 'multselect'"
                :multiple="f.type === 'multselect'"
                class="filter-items_grain"
                v-model="filterForm[f.field]"
                :placeholder="f.placeholder || `请选择${f.label}`"
                @change="(value) => { changeSelect(value, f) }">
                <el-option
                   v-for="(item, index) in f.options"
                  :key="index"
                  :value="f.showSelect === 'item' ? item : (item.value||item.code || item.dictValueCode)"
                  :label="f.showSelect === 'item' ? item : (item.label||item.message|| item.dictValueDesc || item.name)"
                />
              </el-select>
              <el-date-picker
                v-else-if="f.type === 'date'"
                class="filter-items_grain"
                v-model="filterForm[f.field]"
                :disabled-date="f.disabledDate"
                type="daterange"
                unlink-panels
                clearable
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
              <el-date-picker
                v-else-if="f.type === 'date-thirty'"
                class="filter-items_grain"
                v-model="filterForm[f.field]"
                :disabled-date="disabledDateThirty"
                @calendar-change="chooseDay = $event[0]"
                @focus="chooseDay = null"
                type="daterange"
                unlink-panels
                clearable
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
               <el-select
                v-else-if="f.type == 'search_select'"
                v-model="filterForm[f.field]"
                filterable
                ref="searchSelect"
                :placeholder="f.placeholder || `请输入${f.label}`"
                clearable
                class="filter-items_grain"
                :filter-method="handleSearch"
              >
                <el-option
                  v-for="(item, index) in filterOptions"
                  :key="index"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
              <el-cascader
                style="width: 100%"
                :placeholder="f.placeholder || '请选择'"
                v-if="f.type === 'cascader'"
                v-model="filterForm[f.field]" :options="f.options"
                :props="{ value: 'name', label: 'name', checkStrictly: true }"
              />
              <div v-else-if="f.type == 'text'"> {{filterForm[f.field]}}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="!isWrap && showBtn" class='filter-btn'>
          <slot name="before"></slot>
          <el-button style="border-radius: 4px;"  type="primary" @click="onSearch"> 查询 </el-button>
          <el-button v-if="isExport" type="primary" style="margin-left: 10px; border-radius: 4px;" @click="onExport"> {{exportTxt}}
          </el-button>
          <el-button style="border-radius: 4px;" @click="resetForm"> 重置 </el-button>
          <slot name="after"></slot>
        </div>
      </el-form>
      <div v-if="isWrap && showBtn" style="margin: 0 0px 0 36px">
        <slot name="before"></slot>
        <el-button style="border-radius: 4px;" type="primary" @click="onSearch"> 查询 </el-button>
        <el-button v-if="isExport" type="primary" style="margin-left: 10px; border-radius: 4px;" @click="onExport"> {{exportTxt}}
        </el-button>
        <el-button style="border-radius: 4px;" @click="resetForm"> 重置 </el-button>
        <slot name="after"></slot>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
// import { defineComponent, ref, PropType, onMounted, watch } from 'vue'
import { defineComponent, reactive, toRefs } from 'vue'
import dayjs from 'dayjs'
// import { useStore } from 'vuex'
// import { useRoute } from 'vue-router'
import _ from 'lodash'
import { ElConfigProvider } from 'element-plus'

export default defineComponent({
  name: 'ifFilterItems',
  props: {
    fields: {
      type: Array,
      default: () => []
    },
    form: {
      type: Object,
      default: () => { }
    },
    isExport: {
      type: Boolean,
      default: false
    },
    isWrap: {
      type: Boolean,
      default: false
    },
    showBtn: {
      type: Boolean,
      default: true
    },
    exportTxt: {
      type: String,
      default: '导出'
    }
  },
  // computed: {
  //   filterForm() {
  //     const result: any = { ...this.form }
  //     return _.cloneDeep(result)
  //   },
  // },
  components: {
    [(ElConfigProvider as any).name]: ElConfigProvider,
  },
  setup(props, context) {
    const state = reactive({
      filterForm: _.cloneDeep(props.form),
      chooseDay: null
    })

    const disabledDateThirty = (time: any) => {
      if (time.getTime() > Date.now() - 3600 * 1000 * 24) {
        return true
      }
      if (!state.chooseDay) {
        return false
      }
      // 超过30天后禁用
      const after30Days = dayjs(time).isAfter(dayjs(state.chooseDay).add(29, 'day'))
      // 小于30天前禁用
      const before30Days = dayjs(time).isBefore(dayjs(state.chooseDay).subtract(29, 'day'))
      return time.getTime() > Date.now() - 3600 * 1000 * 24 || after30Days || before30Days
    }

    /**
    * 获取格式化数据
    */
    const getFormatData = () => {
      const data: any = { ...state.filterForm }
      const res: any = {}
      Object.keys(data).forEach((key: any) => {
        if (![undefined, null, ''].includes(data[key])) {
          switch (key) {
            default:
              res[key] = data[key]
              break
          }
        }
      })
      return res
    }
    const onSearch = async () => {
      const data = await getFormatData()
      context.emit('change', data)
    }
    // 重置表单
    const resetForm = () => {
      // this.$refs.ruleForm.resetFields();
      const data: any = { ...state.filterForm }
      Object.keys(data).forEach((key: any) => {
        key === 'area' ? state.filterForm[key] = ['全部'] : state.filterForm[key] = undefined
      })
      onSearch()
    }
    const onExport = async () => {
      // const data = await getFormatData()
      context.emit('export')
    }
    const changeSelect = (value: string, option: any) => {
      const data = getFormatData()
      context.emit('selectChange', value, option, data)
    }
    const changeInput = (val: string, option: any) => {
      const res: any = state.filterForm[option.field]
      state.filterForm[option.field] = res.replace(/^\s/, '')
    }
    return {
      ...toRefs(state),
      onSearch,
      onExport,
      getFormatData,
      changeSelect,
      changeInput,
      resetForm,
      disabledDateThirty,
    }
  },
})
</script>

<style scoped lang="less">
.filter-items_grain {
  flex: 1;

  :deep(.el-input__wrapper),
  :deep(.el-input--suffix) {
    width: 100% !important;
  }
  padding:0 30px;
}
.el-form{
  display: flex;
  justify-content: space-between;
}
.el-form-item {
  padding-right: 18px;
}
.el-form-item__label {
  justify-content: flex-start;
}
.filter-btn{
  display: flex;
  align-items: flex-end;
  padding-bottom: 20px;
  padding-left: 20px;
}
</style>
